package cdu.javaendwork.Controller.AdoptionMore;


import cdu.javaendwork.model.sqlModel.*;
import cdu.javaendwork.service.Impl.AdoptionMore.*;
import cdu.javaendwork.service.Impl.User.ConcernServiceImpl;
import cdu.javaendwork.service.Impl.User.UserServiceImpl;
import cdu.javaendwork.service.Interface.AdoptionMore.*;
import cdu.javaendwork.service.Interface.User.ConcernService;
import cdu.javaendwork.service.Interface.User.UserService;
import cdu.javaendwork.util.ProNumber.ProNumBerHelper;
import cdu.javaendwork.util.pageHelp.PageHelper;
import cdu.javaendwork.util.pageHelp.PageInfo;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.*;

@WebServlet({"/post_list","/add_post","/addComment","/collect","/collec_post","/commentList","/del_collect"})
public class PostsController extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String servletPath = req.getServletPath();

        if(servletPath.equals("/post_list")){
            doPost_list(req,resp);
        }else if(servletPath.equals("/add_post")){
            doadd_post(req,resp);
        }else if(servletPath.equals("/addComment")){
            doaddComment(req,resp);
        }else if(servletPath.equals("/collect")){
            docollect(req,resp);
        }
        else if(servletPath.equals("/collec_post")){
            docollec_post(req,resp);
        }
        else if(servletPath.equals("/commentList")){
            docommentList(req,resp);
        }
        else if(servletPath.equals("/del_collect")){
            dodel_collect(req,resp);
        }

    }

    private void dodel_collect(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset = utf-8");
        PrintWriter out=resp.getWriter();
        User user = (User) req.getSession().getAttribute("user");
        int pid=Integer.parseInt(req.getParameter("pid"));

        CollectService collectService=new CollectServiceImpl();
        if(collectService.delete(user.getId(),pid)){
            out.println("<script>alert('取消成功！');window.location.href='collec_post'</script>");
        }
        else{
            out.println("<script>alert('取消失败！');window.location.href='collec_post'</script>");
        }
    }

    private void docommentList(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset = utf-8");
        User user1 = (User) req.getSession().getAttribute("user");
        String pid=req.getParameter("pid");
        int concernid=0;
        int  id = (pid == null || pid.equals("")) ? 1 : Integer.parseInt(pid);

        PostService postService = new PostServiceImpl();
        Post post = postService.findByid(id);
        ConcernService concernService = new ConcernServiceImpl();
        concernid= post.getUserid();
        int uid = user1.getId();
        int flag = 0;
        if(concernService.isConcerned(uid,concernid)) flag = 1;

        int fans = 0;
        fans = concernService.concernedCnt(concernid);

        PetService petService =new PetServiceImpl();
        Pet pet=petService.findById(post.getPetid());

        UserService userService=new UserServiceImpl();
        User userpost=userService.findById(post.getUserid());
        req.setAttribute("pet",pet);
        req.setAttribute("userpost",userpost);
        req.setAttribute("post",post);

        Set<Integer> set = new HashSet<>();
        List<User> userList=new ArrayList<>();

        String sPage = req.getParameter("page");
        int pageIndex = (sPage == null || sPage.equals("")) ? 1 : Integer.parseInt(sPage);
        int pageSize = 4;
        PageHelper pageHelper = new PageHelper();
        PageInfo pageInfo = pageHelper.filter("Remark","postid="+id,pageIndex,pageSize);
        req.setAttribute("pageInfo",pageInfo);

        RemarkService remarkService=new RemarkServiceImpl();
        List<Remark> remarkList=remarkService.limitByPostId(id,pageIndex,pageSize);
        req.setAttribute("remarks",remarkList);
        System.out.println("remarklist:"+remarkList);
        for (Remark remark:remarkList){
            int userid = remark.getUserid();
            if(set.contains(userid)) continue;
            User user= userService.findById(userid);
            userList.add(user);
            set.add(userid);
        }
        req.setAttribute("userList",userList);
        req.setAttribute("flag",flag);
        req.setAttribute("fans",fans);

        req.getRequestDispatcher("content.jsp").forward(req,resp);
    }

    private void docollec_post(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String sPage = req.getParameter("page");
        User user = (User) req.getSession().getAttribute("user");
        int pageSize=4;
        int pageIndex = (sPage == null || sPage.equals("")) ? 1 : Integer.parseInt(sPage);
        PageHelper pageHelper = new PageHelper();
        PageInfo pageInfo = pageHelper.filter("Collect","userid="+user.getId(),pageIndex,pageSize);
        List<Post> postList=new ArrayList<>();
        PostService postService=new PostServiceImpl();
        CollectService collectService = new CollectServiceImpl();
        List<Collect> collectList= collectService.filterByUserIdLimit(user.getId(), pageIndex,pageSize);

        for (Collect collect:collectList){
            System.out.println("collect:"+collect);
            int postid=collect.getPostid();
            Post post= postService.findByid(postid);
            postList.add(post);
        }
        System.out.println(postList);
        UserService userService=new UserServiceImpl();
        Set<Integer> set = new HashSet<>();
        List<User> userList=new ArrayList<>();
        for (Post post:postList){
            int userid = post.getUserid();
            if(set.contains(userid)) continue;
            User users= userService.findById(userid);
            userList.add(users);
            set.add(userid);
        }
        req.setAttribute("postList",postList);
        req.setAttribute("userList",userList);
        req.setAttribute("pageInfo",pageInfo);

        System.out.println(pageInfo);
        System.out.println(userList);

        req.getRequestDispatcher("collect.jsp").forward(req,resp);
    }

    private void docollect(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset = utf-8");
        PrintWriter out=resp.getWriter();
        User user = (User) req.getSession().getAttribute("user");
        int pid=Integer.parseInt(req.getParameter("pid"));

        CollectService collectService=new CollectServiceImpl();
        if(collectService.findByUseridAndPostid(user.getId(),pid).isEmpty()){
            if(collectService.insert(user.getId(),pid)){
                out.println("<script>alert('收藏成功！');window.location.href='post_list'</script>");
            }
            else{
                out.println("<script>alert('收藏失败！');window.location.href='post_list'</script>");
            }
        }
        if (!collectService.findByUseridAndPostid(user.getId(),pid).isEmpty())
            out.println("<script>alert('已收藏！');window.location.href='post_list'</script>");
    }



    private void doaddComment(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset = utf-8");
        User user = (User) req.getSession().getAttribute("user");
        String spid = req.getParameter("pid");

        int uid = user.getId();
        int pid = (spid == null || spid.equals("")) ? 1 : Integer.parseInt(spid);
        String content = req.getParameter("content");

        Remark remark=new Remark();
        remark.setContent(content);
        remark.setDate(new Timestamp(new java.util.Date().getTime()));
        remark.setPostid(pid);
        remark.setUserid(uid);
        remark.setContent(content);

        PrintWriter out=resp.getWriter();
        RemarkService remarkService=new RemarkServiceImpl();
        PostService postService = new PostServiceImpl();
        Post post = postService.findByid(pid);
        req.setAttribute("post",post);


        if(!remarkService.insert(uid,pid,content,new Timestamp(new java.util.Date().getTime()))){
            out.println("<script>alert('评论失败！');window.location.href='"+req.getContextPath()+"/commentList?pid="+pid+"'</script>");
            //    req.getRequestDispatcher("commentList").forward(req,resp);
        }else{
            out.println("<script>alert('评论成功！');window.location.href='"+req.getContextPath()+"/commentList?pid="+pid+"'</script>");
            //  req.getRequestDispatcher("commentList").forward(req,resp);
        }
    }

    private void doadd_post(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Post post=null;
        Pet pet=null;
        resp.setContentType("text/html;charset = utf-8");
        //保存照片位置
        String path = "/WEB-INF/photo";
        //获取真实对应的地址
        String photoUrl = req.getServletContext().getRealPath(path);
        System.out.println(photoUrl);
        //创建一个基于磁盘文件系统的工厂类
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //创建文件上传处理器
        ServletFileUpload upload =new ServletFileUpload(factory);
        try {
            //解析请求
            List<FileItem> items = upload.parseRequest(req);
            if(!items.isEmpty()){
                pet = new Pet();
                post = new Post();
            }
            //创建迭代器，准备处理表单数据
            Iterator<FileItem> iterator = items.iterator();
            while (iterator.hasNext()){
                FileItem item = iterator.next();
                if(item.isFormField()){
                    if(item.getFieldName().equals("title")){
                        post.setTitle(item.getString("utf-8"));
                    }
                    if(item.getFieldName().equals("content")){
                        post.setContent(item.getString("utf-8"));
                    }
                    if(item.getFieldName().equals("petname")){
                        pet.setName(item.getString("utf-8"));
                    }
                    if(item.getFieldName().equals("petkind")){
                        pet.setKind(item.getString("utf-8"));
                    }
                    if(item.getFieldName().equals("description")){
                        pet.setDescription(item.getString("utf-8"));
                    }
                }else {
                    String fileName = item.getName();
                    //防止重复的日期前缀
                    ProNumBerHelper proNumBerHelper = new ProNumBerHelper();
                    String pro = proNumBerHelper.getProNumBerForDate(new Timestamp(new java.util.Date().getTime()).toString());
                    File file = new File(photoUrl+"//"+pro+fileName);
                    item.write(file);
                    pet.setPhoto(req.getContextPath()+path+"/"+pro+fileName);
                }
            }
        } catch (Exception e) {
            System.out.println("上传文件出错："+e.getMessage());
            return;
        }

        PrintWriter out=resp.getWriter();
        PetService petService = new PetServiceImpl();
        int petid=0;
        if(!petService.insert(pet.getName(),pet.getKind(),pet.getPhoto(),pet.getDescription())){
            out.println("<script>alert('添加宠物失败！');window.location.href='write.jsp'</script>");
        }else{
            petid=petService.findByPetnameAndKind(pet.getName(),pet.getKind());
            HttpSession session = req.getSession();
            session.setAttribute("petid",petid);
            // out.println("<script>alert('宠物添加成功！');window.location.href='/'</script>");
        }
        User user = (User) req.getSession().getAttribute("user");
        // System.out.println(user);
        int uid = user.getId();
        // System.out.println(uid);
        post.setDate(new Timestamp(new java.util.Date().getTime()));
        post.setId(uid);
        post.setStatus(1);

        PostService postService = new PostServiceImpl();
        if(!postService.insert(user.getId(),petid,post.getStatus(),post.getTitle(),post.getContent(),post.getDate()))
            out.println("<script>alert('发帖失败！');window.location.href='write.jsp'</script>");
        else
            out.println("<script>alert('发帖成功！');window.location.href='post_list'</script>");
    }


    /**
     *
     * @param req
     * @param resp
     */
    public void doPost_list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String sPage = req.getParameter("page");
        String postKeys=req.getParameter("postKeys");
        req.setAttribute("postKey",postKeys);
        int pageSize=3;
        int pageIndex = (sPage == null || sPage.equals("")) ? 1 : Integer.parseInt(sPage);
        PageHelper pageHelper = new PageHelper();
        PageInfo pageInfo = pageHelper.filter("Post","status=1",pageIndex,pageSize);

        UserService userService=new UserServiceImpl();

        Set<Integer> set = new HashSet<>();
        List<User> userList=new ArrayList<>();
        PostService postService=new PostServiceImpl();
        List<Post> postList=new ArrayList<>();
        if(postKeys==null||postKeys.equals("")) {
            postList = postService.Postlimit(pageIndex, pageSize);
        }else {
            pageInfo=pageHelper.filter("Post","status=1 and (title like '%" + postKeys + "%' or content like '%"+postKeys+"%' )",pageIndex,pageSize);
            postList=postService.filterByTitleAndContentLimit(postKeys,pageIndex,pageSize);
        }
        req.setAttribute("posts",postList);
        for (Post post:postList){
            int userid = post.getUserid();
            if(set.contains(userid)) continue;
            User user= userService.findById(userid);
            userList.add(user);
            set.add(userid);
        }
        req.setAttribute("userList",userList);
        req.setAttribute("pageInfo",pageInfo);

 //       req.getRequestDispatcher("post_manage.jsp").forward(req,resp);



        req.getRequestDispatcher("postList.jsp").forward(req,resp);

    }

}



